package pages

import (
	"black_mamba/global"
	"black_mamba/utils"
	"fmt"
	"gitee.com/wengo/windows_gui/listitemtemplate"
	"gitee.com/wengo/windows_gui/widget"
	"gitee.com/wengo/windows_gui/xc"
	"gitee.com/wengo/windows_gui/xcc"
	"sync"
	"time"
	"unsafe"
)

type Foundation struct {
	ExecuteBtn *widget.Button
	LogEdit    *widget.Edit
	Style      map[string]int
	HAdapter   int
	ListBox    *widget.ListBox
	//ParentLayout  *widget.LayoutEle
	//ListBoxLayout *widget.LayoutEle
	RwMutex sync.RWMutex
	Topic   string
}

func (f *Foundation) NewListBox(listboxName, layoutName string) {
	if f.ListBox != nil {
		return
	}

	f.ListBox = widget.NewListBoxByName(listboxName)
	f.ListBox.EnableMultiSel(false)
	f.ListBox.SetItemHeightDefault(40, 40)
	f.ListBox.SetDrawItemBkFlags(xcc.List_DrawItemBk_Flag_Nothing)
	f.ListBox.SetItemTemplateXML(layoutName)

	template := listitemtemplate.NewListItemTemplate_LoadZipMem(xcc.ListItemTemp_Type_ListBox, global.BM_LAYOUTZIPFILE, layoutName, "")
	f.ListBox.SetItemTemplate(template.Handle)

	f.HAdapter = xc.XAdTable_Create()
	f.ListBox.BindAdapter(f.HAdapter)

	//f.listBox, f.hAdapter = widgets.NewListBox(listboxName, layoutName, nil)

	f.setListBoxStyle(f.ListBox)
	//f.queueProcess()
	//f.redrawListBoxLayout(f.parentLayout, f.listBoxLayout)

	//f.redrawLogWidget()

}

//注册所有订阅者
func (f *Foundation) Subscribes() {
	//订阅日志
	updateLog := f.UpdateLog
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:log", f.Topic), func(data map[string]string) {
		xc.XC_CallUiThread(updateLog, int(uintptr(unsafe.Pointer(&data))))
	})

	//订阅任务列表
	updateTableData := f.UpdateTableData
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:updateTable", f.Topic), func(data map[string]interface{}) {
		xc.XC_CallUiThread(updateTableData, int(uintptr(unsafe.Pointer(&data))))
	})

	//订阅清除日志
	clearLog := f.ClearLog
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:clearLog", f.Topic), func() {
		xc.XC_CallUiThread(clearLog, 0)
	})

}

func (f *Foundation) SetEditStyle() {
	f.Style = map[string]int{
		"info":    f.LogEdit.AddStyleEx("微软雅黑", 10, xcc.FontStyle_Regular, xc.ABGR(255, 255, 0, 255), true),
		"success": f.LogEdit.AddStyleEx("微软雅黑", 10, xcc.FontStyle_Regular, xc.ABGR(0, 255, 0, 255), true),
		"error":   f.LogEdit.AddStyleEx("微软雅黑", 10, xcc.FontStyle_Regular, xc.ABGR(255, 0, 0, 255), true),
	}
}

func (f *Foundation) setListBoxStyle(listbox *widget.ListBox) {
	listboxCallback := f.listBoxStyleCallback
	f.ListBox.RegEventC(xcc.XE_LISTBOX_TEMP_CREATE_END, listboxCallback)
}

func (f *Foundation) listBoxStyleCallback(pItem *xc.ListBox_Item_, nFlag int, pbHandled *bool) int {
	if pItem.Index%2 == 0 {
		//GetTemplateObject， nTempItemId=0 代表的是一整个项（单元格 td）
		xc.XEle_AddBkFill(f.ListBox.GetTemplateObject(int(pItem.Index), 0), xcc.Layout_State_Flag_Layout_Body, xc.ABGR(93, 100, 104, 255))
	}
	return 0
}

func (f *Foundation) ToggleBtn(data int) int {
	btn := *(*widget.Button)(unsafe.Pointer(uintptr(data)))

	if btn.IsEnable() {
		btn.Enable(false)
	} else {
		btn.Enable(true)
	}
	btn.Redraw(true)
	return 0
}

func (f *Foundation) UpdateLog(data int) int {
	f.RwMutex.Lock()
	logInfo := *(*map[string]string)(unsafe.Pointer(uintptr(data)))
	if logInfo != nil {
		text, ok := logInfo["content"]
		if ok {
			content := fmt.Sprintf("【系统提示】 %s: %s -> %s\n", time.Now().Format(`2006-01-02 15:04:05`), logInfo["email"], text)
			utils.WriteFile("log.txt", content)
			f.LogEdit.AutoScroll()
			f.LogEdit.AddTextEx(content, f.Style[logInfo["status"]])
			f.LogEdit.Redraw(true)
		}
	}
	f.RwMutex.Unlock()

	return 0
}

func (f *Foundation) queueProcess() {
	go func() {
		updateLog := f.UpdateLog
		for {
			value, ok := global.BM_QUEUE.Dequeue()
			if ok {
				if value != nil {
					logInfo := value.(map[string]string)
					xc.XC_CallUiThread(updateLog, int(uintptr(unsafe.Pointer(&logInfo))))
				}

			}

			time.Sleep(100 * time.Millisecond)
		}
	}()
}

func (f *Foundation) ClearLog(data int) int {
	f.LogEdit.SelectAll()
	f.LogEdit.DeleteSelect()
	f.LogEdit.Redraw(true)
	return 0
}

func (f *Foundation) UpdateTableData(data int) int {
	tableData := *(*map[string]interface{})(unsafe.Pointer(uintptr(data)))
	f.ListBox.DeleteItemAll()

	// 填充头部
	headers := tableData["headers"].([]string)

	for _, header := range headers {
		xc.XAdTable_AddColumn(f.HAdapter, header)
	}

	// 填充body
	body := tableData["body"].([]map[string]string)
	for _, bd := range body {
		item := xc.XAdTable_AddItemText(f.HAdapter, "")
		for index, header := range headers {
			xc.XAdTable_SetItemText(f.HAdapter, item, index, bd[header])
		}
	}

	f.RedrawListBoxLayout()
	return 0
}

//func (f *Foundation) redrawLogWidget() {
//	f.LogEdit.AutoScroll()
//	//f.LogEdit.AddTextEx(fmt.Sprintf("【系统提示】 %s: %s\n", time.Now().Format(`2006-01-02 15:04:05`),"成功获取任务"), f.style["success"])
//	f.LogEdit.Redraw(true)
//}

func (f *Foundation) RedrawListBoxLayout() {
	//listboxLayout.Show(true)
	//// 需要调整父布局元素才能重绘子布局元素
	//listboxParentLayout.AdjustLayout(0)
	//listboxParentLayout.Redraw(true)

	f.ListBox.RefreshData()

	listboxLayout := widget.NewLayoutEleByHandle(f.ListBox.GetParentEle())
	listboxLayout.Show(true)

	widget.NewLayoutEleByHandle(listboxLayout.GetParentEle()).AdjustLayout(0)
	widget.NewLayoutEleByHandle(listboxLayout.GetParentEle()).Redraw(true)

	//f.ListBoxLayout.Show(true)
	//f.ParentLayout.AdjustLayout(0)
	//f.ParentLayout.Redraw(true)
}
